package com.example.leepong.Game.Engines;

import com.example.leepong.Game.Engine;
import com.example.leepong.Game.Entities.Ball;
import com.example.leepong.Game.Entities.Land;
import com.example.leepong.Game.Entities.Racket;

/**
 * Created by Ichigo on 27/02/14.
 */
public class CollisionDetector {
    private Engine _engine;
    private CollisionManager _collisionManager;

    public CollisionDetector(Engine engine, CollisionManager collisionManager) {
        _engine = engine;
        _collisionManager = collisionManager;
    }

    public boolean Check() {
        boolean handled = CheckLand();

        if (!handled)
            handled = CheckBottomRacket();

        if (!handled)
            handled = CheckTopRacket();

        return handled;
    }

    private boolean CheckLand() {
        Ball ball = _engine.Ball;
        Land land = _engine.Land;

        if (ball.Rect.Right() > land.Rect.Right && ball.IsToRight()) {
            _collisionManager.OnLandRight();
            return true;
        }

        if (ball.Rect.Left() < land.Rect.Left && ball.IsToLeft()) {
            _collisionManager.OnLandLeft();
            return true;
        }

        if (ball.Rect.Top() < land.Rect.Top && ball.IsToTop()) {
            _collisionManager.OnLandTop();
            return true;
        }

        if (ball.Rect.Bottom() > land.Rect.Bottom && ball.IsToBottom()) {
            _collisionManager.OnLandBottom();
            return true;
        }

        return false;
    }

    private boolean CheckBottomRacket() {
        Ball ball = _engine.Ball;
        Racket bottomRacket = _engine.BottomRacket;

        if (ball.IsToBottom()) {
            if (ball.Rect.Bottom() > bottomRacket.Rect.Top()// ball in
                    && ball.Rect.Top() < bottomRacket.Rect.Top() // but not entirely
                    && ball.Rect.CenterX() < bottomRacket.Rect.Right() && ball.Rect.CenterX() > bottomRacket.Rect.Left()) // on the racket with tolerance
            {
                _collisionManager.OnBottomRacket();
                return true;
            }
        }
        return false;
    }

    private boolean CheckTopRacket() {
        Ball ball = _engine.Ball;
        Racket topRacket = _engine.TopRacket;

        if (ball.IsToTop()) {
            if (ball.Rect.Top() < topRacket.Rect.Bottom() // ball in
                    && ball.Rect.Bottom() > topRacket.Rect.Bottom() // but not entirely
                    && ball.Rect.CenterX() < topRacket.Rect.Right() && ball.Rect.CenterX() > topRacket.Rect.Left()) // on the racket with tolerance
            {
                _collisionManager.OnTopRacket();
                return true;
            }

        }
        return false;
    }
}